package com.movie.ui;

import com.movie.service.AdminService;
import com.movie.service.AuthService;
import com.movie.service.MovieService;
import com.movie.service.UserService;
import com.movie.util.DataUtil;
import javax.swing.*;
import java.awt.*;

public class MainUI extends JFrame {
    private AdminService adminService;
    private MovieService movieService;
    private UserService userService;
    private DataUtil dataUtil;

    public MainUI(DataUtil dataUtil, AdminService adminService, MovieService movieService, UserService userService, AuthService authService) {
        this.dataUtil = dataUtil;
        this.adminService = adminService;
        this.movieService = movieService;
        this.userService = userService;

        setTitle("Movie Ticket System");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.CENTER, 500, 100));

        String userRole = showLogin(authService);

        if (userRole == null) {
            System.exit(0); // 用户取消登录
            return;
        }

        dispose(); // 关闭当前 MainUI 窗口

        // 根据用户角色显示相应的界面
        if (userRole.equals("admin")) {
            SwingUtilities.invokeLater(() -> {
                AdminUI adminUI = new AdminUI(adminService, dataUtil);
                adminUI.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                     public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                           System.exit(0);
                       }
                 });
            });
        } else {
            SwingUtilities.invokeLater(()->{
                 UserUI userUI =  new UserUI(movieService, userService, dataUtil);
                 userUI.addWindowListener(new java.awt.event.WindowAdapter() {
                   @Override
                   public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                      System.exit(0);
                   }
                });
           });
        }
    }

    private String showLogin(AuthService authService) {
        LoginUI loginUI = new LoginUI(this, authService);
        return loginUI.getUserRole();
    }

}